package com.tutk.p2p;

import android.content.Context;

import org.eclipse.paho.client.mqttv3.MqttClient;

import java.util.HashMap;

import cn.innosmart.aq.util.LanSearchUtil;
import cn.innosmart.aq.util.NetworkTool;

/**
 * Created by David on 2015/6/26.
 */
public class ConnectionManager {
    public static onConnectInterface onConnectCallback;
    private final int UNKNOWN = 0;
    private final int LAN = 1;
    private final int WLAN = 2;
    public int CONTYPE = 0;
    private ConnectionEntity currentConnectionEntity;
    private HashMap<String, ConnectionEntity> connectionEntities;
    private int MAX_CONNECT_NUM;
    private MqttClient mqttClient;
    private String WlanHost = "tcp://mqtt.innosmart.cn:1883";

    private ConnectionManager() {

    }

    public static ConnectionManager getInstance() {
        return ConnectionManagerInstance.instance;
    }

    public ConnectionEntity getCurrentConnectionEntity() {
        return currentConnectionEntity;
    }

    public void setCurrentConnectionEntity(ConnectionEntity currentConnectionEntity) {
        this.currentConnectionEntity = currentConnectionEntity;
    }

    public MqttClient getMqttClient() {
        return mqttClient;
    }

    public void setMqttClient(MqttClient mqttClient) {
        this.mqttClient = mqttClient;
    }

    public void setOnConnectCallBack(onConnectInterface callBack) {
        onConnectCallback = callBack;
    }

    //检查连接是否存在
    private boolean connectionIsExit(String did) {
        if (connectionEntities == null) {
            return false;
        } else {
            if (connectionEntities.get(did) != null) {
                return true;
            }
            return false;
        }
    }

    // 检查 P2P 是否已经达到最大连接数
    public boolean checkIfMaxConnectReached() {
        return (MAX_CONNECT_NUM == connectionEntities.size());
    }

    // 通过 UID 查找 ConnectionEnty
    public int getConnectModelIndexFromDID(String UID) {
        int index = -1;
        int i = 0;
        int size = connectionEntities.size();
        ConnectionEntity conn;
        for (i = 0; i < size; ++i) {
            conn = connectionEntities.get(i);
            if (UID.equals(conn.getUid())) {
                index = i;
                break;
            }
        }
        return index;
    }

    public ConnectionEntity getConnectionEntityFromUID(String UID) {
        ConnectionEntity conn = null;
        conn = connectionEntities.get(UID);
        return conn;
    }

    public boolean disCurrentConnect() {
        currentConnectionEntity.disConnect();
        connectionEntities.remove(currentConnectionEntity);
        return true;
    }

    /**
     * 创建连接
     *
     * @param did
     * @param userName
     * @param password
     * @param iConnectionEntity
     * @return
     */
    public ConnectionEntity createConnect(Context context, final String did, String userName, String password, IConnectionEntity iConnectionEntity) {
        CONTYPE = UNKNOWN;
        if (connectionEntities == null) {
            connectionEntities = new HashMap<String, ConnectionEntity>();
        }
        if (!connectionIsExit(did)) {
            System.out.println("new Connect");
            currentConnectionEntity = new ConnectionEntity(context, did, userName, password, iConnectionEntity);
        }
        connectionEntities.put(did, currentConnectionEntity);
        onConnectCallback.onConnectStatus(did, 123, 1003);
        //判断是否wifi连接
        if (NetworkTool.getInstance().isWifiConnected(context))
            //局域网搜索
            lanSearch(context, did);
        else {
            //直接连接服务器
            CONTYPE = WLAN;
            currentConnectionEntity.init(CONTYPE, WlanHost);
        }
        return currentConnectionEntity;
    }

    /**
     * 局域网搜索
     *
     * @param context
     * @param did
     */
    private void lanSearch(Context context, final String did) {
        LanSearchUtil.getInstance().search(context, did, new LanSearchUtil.SearchResultInterface() {
            @Override
            public void onResultCallBack(int ret, Object object) {
                if (CONTYPE == 0) {
                    CONTYPE = WLAN;
                    currentConnectionEntity.init(CONTYPE, WlanHost);
                }
            }

            @Override
            public void onResultIPCallBack(String uid, String ip) {
                System.out.println("uid=" + uid + "ip=" + ip);
                if (did.equals(uid)) {
                    CONTYPE = LAN;
                    currentConnectionEntity.init(CONTYPE, ip);
                }
            }
        });
    }

    /**
     * 通过UID断开连接
     * @param Uid
     */
    public void disConnectByUid(String Uid) {
        ConnectionEntity connectionEntity = connectionEntities.get(Uid);
        if (connectionEntity != null) {
            connectionEntities.remove(Uid);
        }
    }

    public interface onConnectInterface {
        void onConnectStatus(String did, int sessionId, int status);
    }

    private static class ConnectionManagerInstance {
        private static final ConnectionManager instance = new ConnectionManager();
    }
}
